import axios from 'axios'
import type { AxiosResponse, AxiosError } from 'axios'
import { useUserStore } from '@/stores/user'
import md5 from 'md5'
import { handleResponseError, handleResponseSuccess } from '@/api/handler'
console.log(APP_MODE === 'development' ? window.origin : APP_URL)
const http = axios.create({
  baseURL: APP_MODE === 'development' ? window.origin : APP_URL,
  timeout: 60000,
})

// 添加请求拦截器
http.interceptors.request.use(
  function (config) {
    const user = useUserStore()
    const timestamp = new Date().getTime()
    config.headers['Authorization'] = user.token ? `Bearer ${user.token}` : ''
    config.headers['Timestamp'] = timestamp
    config.headers['Xwsse'] = md5(`token${user.token}timestamp$${timestamp}`)
    return config
  },
  function (error) {
    return Promise.reject(error)
  },
)

http.interceptors.response.use(
  (response: AxiosResponse) => {
    return handleResponseSuccess(response)
  },
  (error: AxiosError) => {
    handleResponseError(error)
    return Promise.reject(error)
  },
)

export default http
